package com.xyh.springboot.util;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.util.UUID;

/**
 * @Author:kyle
 * @Date:2021/1/4 - 16:14
 * @Project:springboot
 * @Package:com.xyh.springboot.util
 * @Version:1.0
 * 加密加盐工具类
 */
public class ShiroPasswordSaltUtil {
    //加密方式 ALGORITHM算法
    private static final String HASH_ALGORITHM_NAME="MD5";

    /**
     * 生成随机盐值
     * @return
     */
    public static String createSalt(){

        return UUID.randomUUID().toString().replaceAll("-","");
    }

    /**
     * 加密加盐
     * @param password 密码
     * @return
     */
    public static final String md5Salt(String password){

        return md5Salt(password,createSalt());
    }


    public static final String md5Salt(Object password,String salt){
        //盐：为了即使相同的密码，不同的盐加密后的结果也不同
        ByteSource byteSalt = ByteSource.Util.bytes(salt);
        System.out.println("盐值 = " + salt);
        System.out.println("byteSalt = " + byteSalt);
        //加密次数
        int hashIterations = 1024;

        //加密方式，密码，盐值，加密次数
        SimpleHash simpleHash = new SimpleHash(HASH_ALGORITHM_NAME,password,byteSalt,hashIterations);

        return simpleHash.toString();
    }

}
